package com.ck.controller.teacher;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Teacher;
import com.ck.service.TeacherService;

public class EditTeacherOwnInfoController extends SimpleFormController {

	private TeacherService teacherService;
	
	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer teacherID = (Integer) request.getSession().getAttribute("teacherID");
		Teacher teacher = teacherService.gainTeacher(teacherID);
		return teacher;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

		Teacher teacher = (Teacher) command;
		Map model = errors.getModel();
		
		//后台校验
        boolean flag = true;
        String email = teacher.getEmail().trim();
        
        if( email == null || "".equals(email) ){
        	teacher.setEmail(null);
        }else{
	        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			if(!m.matches()){
				model.put("error_email", "email格式不正确");
				flag = false;
			}
        }
		
		if(email.length() > 40){
			model.put("error_email", "email长度：0-40个字符");
			flag = false;
		}
        
		//校验不通过
		if(!flag){
			return new ModelAndView(getFormView(), model);
		}
		
		Integer teacherID = (Integer) request.getSession().getAttribute("teacherID");
		teacher.setId(teacherID);
        
        boolean isEditTeacherOwnInfo = teacherService.editTeacherOwnInfo(teacher);

        if (isEditTeacherOwnInfo) {
            return new ModelAndView(getSuccessView(), model);
        } else {
            return new ModelAndView(getFormView(), model);
        }
    }
}
